import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from "@/views/LoginView.vue";
import RegisterView from "@/views/RegisterView.vue";
import UserView from "@/views/UserView.vue";
import UserListView from "@/views/UserListView.vue";
import DashboardView from "@/views/DashboardView.vue";
import { getToken } from "@/utils/token";
import ElementUI from 'element-ui';

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'userLogin',
    component: LoginView,
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    children: [
      {
        path: '',
        name: 'dashboard',
        component: DashboardView
      },
      {
        path: '/users',
        name: 'userList',
        component: UserListView
      }
    ]
  },
  {
    path: '/register',
    name: 'register',
    component: RegisterView
  },
  {
    path: '/user',
    name: 'user',
    component: UserView
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫,检查是否需要登录
router.beforeEach((to, from, next) => {
 if(to.path === '/login' || to.path === '/register'){
  next();
 } else {
  if(getToken()){
    next();
  } else {
    // 没有token，重定向到登录页
    ElementUI.Message.error('请先登录');
    next(('/login'));
  }
  
 }
});

export default router
